import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/build_gen/assets.gen.dart';
import 'package:casdon/common/utils/string_externtion.dart';
import 'package:casdon/common/widget/common_loading_widget.dart';
import 'package:casdon/modules/me/application/notification/browsing_life_history_notifier.dart';
import 'package:casdon/modules/me/data/model/browsing_life_history_model.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:casdon/auto_router.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

/// 生活圈浏览记录子页面
class BrowsingLifeHistoryScreen extends ConsumerWidget {
  const BrowsingLifeHistoryScreen({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final state = ref.watch(browsingLifeHistoryNotifierProvider);
    final notifier = ref.read(browsingLifeHistoryNotifierProvider.notifier);

    return RefreshIndicator(
      onRefresh: () => notifier.refresh(),
      child: NotificationListener<ScrollNotification>(
        onNotification: (notification) {
          if (notification is ScrollEndNotification &&
              notification.metrics.pixels >=
                  notification.metrics.maxScrollExtent - 50) {
            notifier.loadMore();
          }
          return false;
        },
        child: state.when(
          loading: () => const Center(child: CommonLoadingWidget()),
          error: (e, _) => Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text('加载失败'),
                const SizedBox(height: 16),
                ElevatedButton(
                  onPressed: () => notifier.refresh(),
                  child: const Text('重试'),
                ),
              ],
            ),
          ),
          data: (historyState) {
            if (historyState.data.isEmpty) {
              return _buildEmptyState(context);
            }

            final grouped = historyState.groupedByDate;
            final groupedEntries = grouped.entries.toList();

            return ListView.builder(
              key: const PageStorageKey('life_history_list'),
              padding: EdgeInsets.symmetric(vertical: 8.h),
              itemCount: groupedEntries.length,
              itemBuilder: (context, dateIndex) {
                final dateEntry = groupedEntries[dateIndex];
                final date = dateEntry.key;
                final items = dateEntry.value;

                return Column(
                  key: ValueKey('date_group_$date'),
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 日期标题
                    Padding(
                      padding: EdgeInsets.symmetric(
                        horizontal: 16.w,
                        vertical: 8.h,
                      ),
                      child: Row(
                        children: [
                          Container(
                            width: 10.w,
                            height: 10.w,
                            decoration: BoxDecoration(
                              color: context.colorScheme.primary,
                              shape: BoxShape.circle,
                            ),
                          ),
                          SizedBox(width: 8.w),
                          Text(
                            date,
                            style: context.textTheme.bodyMedium!.copyWith(
                              color: context.customColorThemeNonNull.textColor3,
                            ),
                          ),
                        ],
                      ),
                    ),
                    // 列表项
                    ...items.asMap().entries.map((entry) {
                      final index = entry.key;
                      final item = entry.value;
                      return _buildHistoryItem(context, item, date, index);
                    }),
                  ],
                );
              },
            );
          },
        ),
      ),
    );
  }

  Widget _buildHistoryItem(
    BuildContext context,
    BrowsingLifeHistoryModel item,
    String date,
    int index,
  ) {
    return InkWell(
      key: ValueKey('life_item_${item.id}_${date}_$index'),
      onTap: () {
        LifeTopicDetailRoute(topicId: item.id).push(context);
      },
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: 12.w, vertical: 4.h),
        padding: EdgeInsets.all(6.w),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(8),
        ),
        child: Row(
          children: [
            // 图片
            item.mainImg != null && item.mainImg!.isNotEmpty
                ? ClipRRect(
                    borderRadius: BorderRadius.circular(6),
                    child: CachedNetworkImage(
                      cacheKey: item.id,
                      imageUrl: item.mainImg!.cropParams300,
                      width: 64.w,
                      height: 64.w,
                      fit: BoxFit.cover,
                      placeholder: (context, url) => Container(
                        width: 64.w,
                        height: 64.w,
                        color: Colors.grey[200],
                      ),
                      errorWidget: (context, url, error) => Container(
                        width: 64.w,
                        height: 64.w,
                        color: Colors.grey[200],
                        child: Icon(
                          Icons.image_outlined,
                          color: Colors.grey[400],
                        ),
                      ),
                    ),
                  )
                : SizedBox(width: 1.w, height: 64.w),

            SizedBox(width: 12.w),

            // ⭐ 标题区域必须 Expanded，限制宽度
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '@${item.author}',
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: context.textTheme.bodyMedium!.copyWith(
                      color: context.customColorThemeNonNull.textColor1,
                    ),
                  ),
                  SizedBox(height: 5.h),
                  Text(
                    item.title,
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: context.textTheme.bodySmall!.copyWith(
                      color: context.customColorThemeNonNull.textColor2,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildEmptyState(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image(
            image: Assets.images.emptyData.provider(),
            width: 106.w,
            height: 68.w,
          ),
          SizedBox(height: 16.h),
          Text(
            "暂无数据",
            style: context.textTheme.bodyMedium!.copyWith(
              color: context.customColorThemeNonNull.textColor2,
            ),
          ),
        ],
      ),
    );
  }
}
